package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;

	@Autowired
	private ItemDescMapper itemDescMapper;


	@Override
	public EasyUITable findItemByPage(Integer page, Integer rows) {
	//条件构造器
		QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("updated");
		// 暂时只封装了2个数据 页数/条数
		IPage<Item> iPage = new Page<>(page,rows);
		iPage = itemMapper.selectPage(iPage,queryWrapper);
		//获取分页的总记录数
		Long total = iPage.getTotal();

		List<Item> list = iPage.getRecords();
		return new EasyUITable(total,list);
		/*// 1 手动完成分页操作
		int startIndex = (page-1) * rows;

		//2 数据库记录
		List<Item> itemList = itemMapper.findItemByPage(startIndex,rows);

		//3 查询数据库的总记录数
		Long total = Long.valueOf(itemMapper.selectCount(null));
		//4 讲数据库记录封装到vo对象
		return new EasyUITable(total,itemList);*/

	}

	@Override
	@Transactional //控制事务
	public void saveItem(Item item, ItemDesc itemDesc) {

//		Date date = new Date();
		//完成自动填充功能
//		item.setStatus(1).setCreated(date).setUpdated(date);
		item.setStatus(1);
		itemMapper.insert(item);

		itemDesc.setItemId(item.getId());
		itemDescMapper.insert(itemDesc);
	}

	@Transactional //控制事务
	@Override
	public void updateItem(Item item, ItemDesc itemDesc) {
		//更新时间由程序自动填充
		itemMapper.updateById(item);

		itemDesc.setItemId(item.getId());
		itemDescMapper.updateById(itemDesc);
	}

	@Override
	public void deleteItems(Long[] ids) {

		//将数组转化为集合
		List<Long> longList = Arrays.asList(ids);
		itemMapper.deleteBatchIds(longList);
		itemDescMapper.deleteBatchIds(longList);
	}

	@Override
	public void updateStatus(Integer status, Long[] ids) {
		Item item = new Item();
		item.setStatus(status);
		UpdateWrapper<Item> updateWrapper = new UpdateWrapper<>();
		updateWrapper.in("id", Arrays.asList(ids));
		itemMapper.update(item,updateWrapper);
	}

	@Override
	public ItemDesc findItemDescById(Long itemId) {
		return itemDescMapper.selectById(itemId);
	}


}
